package com.kiln.juxingqs.ui

import android.content.IntentFilter
import android.view.KeyEvent
import androidx.lifecycle.Observer
import androidx.navigation.NavController
import androidx.navigation.findNavController
import androidx.navigation.ui.setupWithNavController
import client.global.commlib.toast.toast
import com.kiln.juxingqs.BaseMiddleActivity
import com.kiln.juxingqs.R
import com.kiln.juxingqs.databinding.ActivityMainBinding
import com.kiln.juxingqs.receiver.MeBroadcast
import com.kiln.juxingqs.ui.vm.MainViewModel
import java.util.*

class MainActivity : BaseMiddleActivity<MainViewModel, ActivityMainBinding>() {

    override fun getLayout(): Int {
        return R.layout.activity_main
    }

    val controller: NavController by lazy {
        findNavController(R.id.nav_host_fragment)
    }

    val meBroadcast: MeBroadcast by lazy {
        MeBroadcast()
    }

    override fun initViewModel(): MainViewModel = createViewModel()

    override fun initView() {
        binding.vm = viewModel
        registerReceiver(meBroadcast, IntentFilter(MeBroadcast.MAIN_SWITCH_TAB))
        binding.navView.setupWithNavController(controller)

    }

    override fun observerUI() {
        viewModel.switchValue.observe(this, Observer {
            if (it >= 0) {
                when (it) {
                    1 -> {
                        controller.navigate(R.id.navigation_jy)
                    }
                    2 -> {
                        controller.navigate(R.id.navigation_news)
                    }
                    0 -> {
                        controller.navigate(R.id.navigation_home)
                    }
                }

                viewModel.switchValue.value = -1
            }
        })

    }

    fun switchTab(tab: Int) {
        viewModel.switchValue.value = tab
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            exitLogin()
        }
        return false
    }

    override fun onDestroy() {
        super.onDestroy()
        unregisterReceiver(meBroadcast)
    }


    private var isExit = false

    private fun exitLogin() {
        var tExit: Timer? = null
        if (!isExit) {
            isExit = true
            toast("再次返回退出" + getString(R.string.app_name))
            tExit = Timer()
            tExit.schedule(object : TimerTask() {
                override fun run() {
                    isExit = false //取消退出
                }
            }, 2500) // 如果2.5秒钟内没有按下返回键，则开启定时器取消掉刚才执行的任务
        } else {
            System.exit(0)
        }
    }

}